package lc.elensliu.ipcservice;

import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

import com.ipc.aidl.implement.Constants;
import com.ipc.aidl.implement.IMessageBinder;
import com.ipc.aidl.implement.IMessageCallback;

public class AIDLService extends Service {


    private final RemoteCallbackList<IMessageCallback> callbackList = new RemoteCallbackList<> ();

    private final IMessageBinder.Stub mBinder = new IMessageBinder.Stub () {

        @Override
        public boolean onTransact (int code, Parcel data, Parcel reply, int flags) throws RemoteException {

            int check = checkCallingOrSelfPermission (Constants.PERMISSION);

            if (check == PackageManager.PERMISSION_DENIED) {

                Log.w ("AIDLService",
                       "[IService onBind] check == PackageManager.PERMISSION_DENIED");
                return false;
            }
            String packageName = "";
            String[] packages = getPackageManager ().getPackagesForUid (getCallingUid ());
            if (packages != null && packages.length > 0) {
                packageName = packages[0];
            }
            if (!packageName.equals (Constants.CHECK_PACKAGENAME)) {

                Log.w ("AIDLService",
                       "[IService onBind] packageName fail :" + packageName);
                return false;
            }

            return super.onTransact (code,
                                     data,
                                     reply,
                                     flags);
        }

        @Override
        public void sendMessage (String message) throws RemoteException {

            int n = callbackList.beginBroadcast ();
            for (int i = 0; i < n; i++) {

                callbackList.getBroadcastItem (i)
                            .onMessageCallback (message + "_aidl_callback");
            }
            callbackList.finishBroadcast ();
        }

        @Override
        public void registerCallback (IMessageCallback callback) throws RemoteException {

            if (callback != null) {
                callbackList.register (callback);
            }

        }

        @Override
        public void unregisterCallback (IMessageCallback callback) throws RemoteException {

            if (callback != null) {
                callbackList.unregister (callback);
            }
        }
    };

    public AIDLService () {
    }


    @Override
    public IBinder onBind (Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException ("Not yet implemented");
        return mBinder;
    }
}
